#include "modbuswig.h"
#include "ui_modbuswig.h"
#include <QDebug>
#include "globalval.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
ModbusWig::ModbusWig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ModbusWig)
{
    ui->setupUi(this);
}

ModbusWig::~ModbusWig()
{
    delete ui;
}
struct DeviceData {
    int key;
    QString name;
    QVariant data; // 使用QVariant来存储不同类型的数据(false/true/数值)
};

void ModbusWig::parse(const QByteArray &msg)
{

       QJsonDocument doc = QJsonDocument::fromJson(msg);


       if (!doc.isObject()) {
           qDebug() << "Document is not an object";
           return;
       }

       QJsonObject obj = doc.object();
       if (!obj.contains("data") || !obj["data"].isArray()) {
           qDebug() << "Invalid JSON format - missing 'data' array";
           return;
       }

       QJsonArray dataArray = obj["data"].toArray();
       QList<DeviceData> deviceList;

       QJsonArray::const_iterator it;
       for (it = dataArray.constBegin(); it != dataArray.constEnd(); ++it) {
           const QJsonValue &value = *it;

           QJsonObject obj = value.toObject();
           DeviceData device;

           device.key = obj["key"].toInt();
           device.name = obj["name"].toString();

           // 根据数据类型处理data字段
           if (obj["data"].isBool()) {
               device.data = obj["data"].toBool();
           } else if (obj["data"].isDouble()) {
               device.data = obj["data"].toDouble();
           } else if (obj["data"].isString()) {
               // 处理字符串形式的布尔值
               QString strData = obj["data"].toString().toLower();
               if (strData == "true" || strData == "false") {
                   device.data = (strData == "true");
               } else {
                   device.data = strData;
               }
           }
 qDebug() <<"*************************************************************";
           deviceList.append(device);
    if(device.name == "tem")
    {
        ui->tem_lcd->display(device.data.toDouble());

    }

    if(device.name == "hum")
    {
        ui->hum_lcd->display(device.data.toDouble());

    }

    if(device.name == "light")
    {
        ui->sun_lcd->display(device.data.toDouble());

    }

           // 打印解析结果
           qDebug() << "Key:" << device.key
                    << "Name:" << device.name
                    << "Data:" << device.data;
       }




}



void ModbusWig::on_shuaxin_Button_clicked()
{
    QMQTT::Message msg;
    msg.setTopic(TOPIC_CTL_DOWN);
    QByteArray payload = "{\"key\":3,\"name\":\"refresh\",\"data\":null}";
    msg.setPayload(payload);
    GlobalVal::mqtt->publish(msg);

}
